package com.kr.laone;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class MediaPlayerView extends View implements OnCompletionListener, OnSeekCompleteListener{

	private MediaPlayer player;
	
	public MediaPlayerView(Context context) {
		super(context);
		setBackgroundColor(Color.WHITE);
		setFocusable(true);
		player = null;
		
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setTextSize(32);
		canvas.drawText("MediaPlayerEx", 0, 40, paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			if(player == null){
				playSound();
			}else{
				stopSound();
			}
				
		}
		return true;
	}

	public void stopSound() {
		try{
			if(player == null) return;
			
			player.stop();
			player.setOnCompletionListener(null);
			player.release();
			player = null;
			
		}catch(Exception e){
			
		}
		
		
	}

	public void playSound() {
		try{
			stopSound();
			
			player = MediaPlayer.create(getContext(), R.raw.sample);
			
			player.seekTo(0);
			player.start();
			
			player.setOnSeekCompleteListener(this);
			player.setOnCompletionListener(this);

		}catch(Exception e){
			
		}
		
	}

	public void onCompletion(MediaPlayer mp) {
		stopSound();
		
	}

	public void onSeekComplete(MediaPlayer mp) {
		Log.d("dd", "onSeekComplete"+mp.getCurrentPosition());
		
	}

	public int getTime() {		
		return player.getCurrentPosition();
	}

	public int getMaxTime() {
		// TODO Auto-generated method stub
		return player.getDuration();
	}
	
	public boolean isPlayer(){
		if(player != null)	return true;
		else return false;
	}

}
